package pub.lichao.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 使用redis进行文章已读控制
 */
@Controller
public class ArticleController {

    @Autowired JedisUtil jedisUtil;

    public List<Article> articleList = new ArrayList<Article>();

    /**
     * 构造方法初始化一组文章
     * 真实情况一般是从数据库中查询
     */
    public ArticleController(){
        for( int i = 1;i <= 20 ;i++){
            Article article = new Article();
            article.setId(Long.valueOf(i));
            article.setTitle("测试文章" + i );
            articleList.add(article);
        }
    }

    /**
     * 阅读文章
     * @param articleId 文章id
     * @param personId 读者id
     * @param model
     * @return
     */
    @RequestMapping(value = "/readArticle", method = RequestMethod.GET)
    public String readArticle(Long articleId,Long personId,ModelMap model){
        //在redis中增加阅读用户id
        jedisUtil.addSet(0,articleId.toString(),personId.toString());
        return "redirect:articleList?personId="+personId;
    }

    /**
     * 文章列表查询
     * @param personId 读者id
     * @param model
     * @return
     */
    @RequestMapping(value = "/articleList", method = RequestMethod.GET)
    public String articleList(Long personId,ModelMap model){
        if(personId == null){
            return "article";
        }

        List<Article> returnArticleList = new ArrayList<Article>();
        Integer unreadArticleNum = 0; //未读文章计数
        for(Article article:articleList){
            Article returnArticle = new Article();
            returnArticle.setId(article.getId());
            returnArticle.setTitle(article.getTitle());
            returnArticle.setIsRead(article.getIsRead());

            //获取redis存储的已读用户列表
            Set<String> personSet = jedisUtil.getSet(0,article.getId().toString());
            boolean b = personSet.contains(personId.toString());
            if(b == true){
                returnArticle.setIsRead(1); //如果存在则更改已读标志
            }else{
                unreadArticleNum++; //如果不存在未读计数加1
            }
            returnArticleList.add(returnArticle);
        }

        model.addAttribute("returnArticleList",returnArticleList);
        model.addAttribute("unreadArticleNum",unreadArticleNum);
        model.addAttribute("personId",personId);

        return "article";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "redirect:articleList";
    }

}
